﻿using System; 
using System.Web;
using System.IO;
using NVelocity;
using NVelocity.App;
using NVelocity.Context;
using NVelocity.Runtime;
using Commons.Collections;


/// <summary>
/// NVelocity模板工具类 NVelocityHelper
/// </summary>
public class NVelocityHelper
{
    private VelocityEngine velocity = null;
    private IContext context = null;
    private string templateDir;
    private string fileName;


    public NVelocityHelper()
        : this(HttpContext.Current.Server.MapPath("~/Template/"), null)
    {
    }


    public NVelocityHelper(string templateDir)
        : this(templateDir, null)
    {
    }

    public NVelocityHelper(string templateDir, string fileName)
    {
        this.templateDir = templateDir;
        this.fileName = fileName;
        //创建VelocityEngine实例对象
        velocity = new VelocityEngine();
        //使用设置初始化VelocityEngine
        ExtendedProperties props = new ExtendedProperties();
        props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
        props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templateDir);
        props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
        props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
        velocity.Init(props);

        //为模板变量赋值
        context = new VelocityContext();
    }

    /// <summary>
    /// 给模板变量赋值
    /// </summary>
    /// <param name="key">模板变量</param>
    /// <param name="value">模板变量值</param>
    public void Add(string key, object value)
    { 
        context.Put(key, value);
    }


    /// <summary>
    /// 通过获得模板文件生成结果字符串
    /// </summary> 
    public string Output()
    {
        return this.Output(this.fileName);
    }

    /// <summary>
    /// 通过获得模板文件生成结果字符串
    /// </summary> 
    public string Output(string fileName)
    {
        //从文件中读取模板
        Template template = velocity.GetTemplate(fileName);
        //合并模板
        StringWriter writer = new StringWriter();
        template.Merge(context, writer);
        //输出
        string retValue = writer.GetStringBuilder().ToString();
        writer.Flush();
        writer.Close();
        writer.Dispose();
        return retValue;
    }
}